<template>
  <div class="article-section" :style="{ width: width + '%' }">
    <!-- 单词状态提示 -->
    <div v-if="isHighlightActive" class="word-status-legend">
      <div class="legend-item">
        <span class="status-dot normal"></span>
        <span>未标记</span>
      </div>
      <div class="legend-item">
        <span class="status-dot known"></span>
        <span>认识</span>
      </div>
      <div class="legend-item">
        <span class="status-dot fuzzy"></span>
        <span>模糊</span>
      </div>
      <div class="legend-item">
        <span class="status-dot unknown"></span>
        <span>不认识</span>
      </div>
    </div>
    
    <div class="article-title">{{ title }}</div>
    <div class="ai-generated-label">内容由AI生成</div>
    <div class="article-content" @mousedown.prevent ref="articleContentRef">
      <p v-for="(paragraph, index) in paragraphs" :key="index" class="paragraph">
        <span v-html="highlightParagraph(paragraph)"></span>
      </p>
    </div>
    
    <!-- 单词提示 Tooltip -->
    <div id="word-tooltip" class="word-tooltip" ref="tooltipRef">
      {{ currentTooltipText }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue';
import { patchWordStatus } from '@/api/readings';
import useWordHighlight from '@/composables/useWordHighlight';

const props = defineProps({
  width: {
    type: Number,
    required: true
  },
  title: {
    type: String,
    required: true
  },
  paragraphs: {
    type: Array,
    required: true
  },
  vocabularyWords: {
    type: Array,
    default: () => []
  },
  isHighlightActive: {
    type: Boolean,
    default: false
  },
  isSubmitted: {
    type: Boolean,
    default: false
  },
  wordVariationsMap: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['word-status-change']);

// 文章内容DOM引用
const articleContentRef = ref(null);
const tooltipRef = ref(null);
const showTooltip = ref(false);
const currentTooltipText = ref('');

// 使用单词高亮组合式API
const {
  highlightParagraph,
  handleWordClick,
  updateWordList,
  updateWordStatus: updateHighlightWordStatus,
  getWordStatus,
  getWordClass,
  getWordForms,
  WORD_STATUS,
  wordList
} = useWordHighlight({
  words: props.vocabularyWords,
  paragraphs: props.paragraphs,
  isHighlightActive: props.isHighlightActive,
  wordVariationsMap: props.wordVariationsMap
});

// 监听单词列表变化
watch(() => props.vocabularyWords, (newWords) => {
  if (newWords && newWords.length > 0) {
    updateWordList(newWords);
  }
}, { deep: true });

// 监听高亮状态变化
watch(() => props.isHighlightActive, () => {
  // 不再需要调用updateUnhighlightedWords
});

// 监听变形词映射变化
watch(() => props.wordVariationsMap, () => {
  updateWordList(props.vocabularyWords);
}, { deep: true });

// 防抖处理的API调用 - 为每个单词ID维护单独的状态更新
const wordUpdateTimers = new Map();

// 更新单词状态到后端
const updateWordStatusInBackend = (wordData) => {
    const { id, status } = wordData;
    if (!id) return;
    
  // 清除该单词之前的定时器（如果存在）
  if (wordUpdateTimers.has(id)) {
    clearTimeout(wordUpdateTimers.get(id));
  }
  
  // 为该单词设置新的定时器
  const timerId = setTimeout(async () => {
    try {
    // 根据状态更新对应的计数
    let recognized_count = 0;
    let unrecognized_count = 0;
    let ambiguous_count = 0;
    
    if (status === WORD_STATUS.KNOWN) {
      recognized_count = 1;
    } else if (status === WORD_STATUS.FUZZY) {
      ambiguous_count = 1;
    } else if (status === WORD_STATUS.UNKNOWN) {
      unrecognized_count = 1;
    }
    
    // 调用API更新单词状态
    const response = await patchWordStatus({
      id,
      status,
      quality: status === WORD_STATUS.KNOWN ? 5 : (status === WORD_STATUS.FUZZY ? 3 : 1),
      recognized_count,
      unrecognized_count,
      ambiguous_count
    });
    
    console.log('单词状态更新成功:', response);
  } catch (error) {
    console.error('更新单词状态失败:', error);
    } finally {
      // 完成后从Map中删除该定时器
      wordUpdateTimers.delete(id);
    }
  }, 1000);
  
  // 存储定时器ID
  wordUpdateTimers.set(id, timerId);
};

// 挂载DOM事件监听
onMounted(() => {
  // 初始化tooltip状态
  if (tooltipRef.value) {
    tooltipRef.value.style.visibility = 'hidden';
    tooltipRef.value.style.display = 'none';
  }

  // 为文章容器添加点击事件委托
  if (articleContentRef.value) {
    articleContentRef.value.addEventListener('click', handleArticleClick);
    
    // 添加鼠标悬停事件监听
    articleContentRef.value.addEventListener('mouseover', handleWordHover);
    articleContentRef.value.addEventListener('mouseout', handleWordHoverEnd);
  }
});

// 处理文章内容点击
const handleArticleClick = (event) => {
  // 如果文章已提交，阻止修改单词状态
  if (props.isSubmitted) {
    console.log('文章已提交，不能修改单词状态');
    return;
  }
  
  const result = handleWordClick(event);
  if (result) {
    const { word, status } = result;
    
    // 查找原词和所有变形词
    const wordForms = getWordForms(word);
    
    // 为所有形式更新状态
    wordForms.forEach(formWord => {
      // 查找词汇对象并更新API
      const wordObj = findWordObject(formWord);
      if (wordObj && wordObj.study_status && wordObj.study_status.id) {
        // 发送状态变更事件
        emit('word-status-change', { word: formWord, status });
        
        // 更新到后端
        updateWordStatusInBackend({
          id: wordObj.study_status.id,
          status
        });
      }
    });
  }
};

// 查找单词对象
const findWordObject = (word) => {
  return props.vocabularyWords.find(w => 
    w.content.toLowerCase() === word.toLowerCase()
  );
};

// 处理单词悬停事件
const handleWordHover = (event) => {
  const target = event.target;
  
  // 检查是否悬停在单词上
  if (target.classList.contains('vocab-word')) {
    // 如果是灰色状态（未标记状态）的单词，不显示提示
    if (target.classList.contains('word-normal')) {
      return;
    }
    
    const translation = target.getAttribute('data-translation');
    
    if (translation) {
      // 先设置内容但不显示
      currentTooltipText.value = translation;
      
      // 计算位置 - 默认在单词上方显示
      const rect = target.getBoundingClientRect();
      const tooltip = tooltipRef.value;
      
      if (tooltip) {
        // 先确保tooltip是隐藏的状态下计算位置
        tooltip.style.visibility = 'hidden';
        tooltip.style.display = 'block';
        
        // 使用nextTick确保DOM已更新内容
        nextTick(() => {
          const tooltipRect = tooltip.getBoundingClientRect();
          
          // 获取单词元素的中心位置
          const wordCenterX = rect.left + (rect.width / 2);
          
          // 默认在单词上方显示
          let topPosition = rect.top - 10;
          
          // 检查是否会超出视口顶部
          if (topPosition - tooltipRect.height < 10) {
            // 如果会超出顶部，则显示在单词下方
            topPosition = rect.bottom + 10;
            tooltip.style.transform = 'translateX(-50%)';
          } else {
            // 在上方显示时，向上偏移自身高度
            topPosition -= tooltipRect.height;
            tooltip.style.transform = 'translateX(-50%)';
          }
          
          tooltip.style.left = `${wordCenterX}px`;
          tooltip.style.top = `${topPosition}px`;
          
          // 位置设置完成后，显示tooltip
          tooltip.style.visibility = 'visible';
          showTooltip.value = true;
        });
      }
    }
  }
};

// 处理单词悬停结束事件
const handleWordHoverEnd = () => {
  showTooltip.value = false;
  if (tooltipRef.value) {
    tooltipRef.value.style.visibility = 'hidden';
  }
};

// 检查是否所有高亮单词都已标记状态（非灰色状态）
const areAllWordsMarked = () => {
  if (!wordList.value || wordList.value.length === 0) {
    console.log('没有单词需要标记');
    return true; // 如果没有单词，认为已全部标记
  }
  
  // 获取所有未标记状态的高亮单词
  const unmarkedWords = getUnmarkedHighlightedWords();
  
  console.log(`检查单词标记状态: 总共高亮单词中，未标记${unmarkedWords.length}个`);
  if (unmarkedWords.length > 0) {
    console.log('未标记的单词:', unmarkedWords.map(w => w.content));
  }
  
  return unmarkedWords.length === 0;
};

// 获取所有未标记的高亮单词
const getUnmarkedHighlightedWords = () => {
  // 使用Map记录所有单词及其状态
  const wordStatusMap = new Map();
  
  // 收集已高亮的单词
  const highlightedWordSet = new Set();
  
  // 检查文章中所有的.vocab-word元素
  if (articleContentRef.value) {
    const highlightedElements = articleContentRef.value.querySelectorAll('.vocab-word');
    highlightedElements.forEach(el => {
      const word = el.getAttribute('data-word');
      if (word) highlightedWordSet.add(word.toLowerCase());
    });
  }
  
  // 记录每个单词的状态
  wordList.value.forEach(word => {
    const content = word.content.toLowerCase();
    let status = word.status;
    
    if (word.study_status && typeof word.study_status.status === 'number') {
      status = word.study_status.status;
    }
    
    wordStatusMap.set(content, status);
  });
  
  // 处理变形词关系
  Object.entries(props.wordVariationsMap).forEach(([originalWord, variations]) => {
    const originalLower = originalWord.toLowerCase();
    const originalStatus = wordStatusMap.get(originalLower);
    
    // 如果原词已标记，则所有变形词也视为已标记
    if (originalStatus !== undefined && originalStatus !== WORD_STATUS.NORMAL) {
      variations.forEach(variation => {
        if (variation) {
          wordStatusMap.set(variation.toLowerCase(), originalStatus);
        }
      });
    } else {
      // 检查变形词是否有任何一个被标记
      let bestStatus = WORD_STATUS.NORMAL;
      
      variations.forEach(variation => {
        if (!variation) return;
        
        const variationLower = variation.toLowerCase();
        const varStatus = wordStatusMap.get(variationLower);
        if (varStatus !== undefined && varStatus !== WORD_STATUS.NORMAL) {
          bestStatus = varStatus;
        }
      });
      
      // 如果找到已标记的变形词，更新原词和所有变形
      if (bestStatus !== WORD_STATUS.NORMAL) {
        wordStatusMap.set(originalLower, bestStatus);
        variations.forEach(variation => {
          if (variation) {
            wordStatusMap.set(variation.toLowerCase(), bestStatus);
          }
        });
      }
    }
  });
  
  // 过滤出未标记的高亮单词
  return wordList.value.filter(word => {
    const content = word.content.toLowerCase();
    
    // 检查原词和变形词是否有任何一个被高亮
    const allForms = getWordForms(content);
    
    // 检查是否有任何形式被高亮但未标记
    for (const form of allForms) {
      if (highlightedWordSet.has(form)) {
        const status = wordStatusMap.get(form);
        if (status === undefined || status === WORD_STATUS.NORMAL) {
          return true; // 找到了高亮但未标记的形式
        }
      }
    }
    
    return false; // 所有高亮的形式都已标记，或者没有形式被高亮
  });
};

// 聚焦未标记的单词（添加高亮效果）
const focusUnmarkedWords = () => {
  const unmarkedWords = getUnmarkedHighlightedWords();
  
  if (unmarkedWords.length === 0) {
    return [];
  }
  
  // 收集所有未标记单词及其变形词
  const allUnmarkedForms = new Set();
  
  // 将未标记单词及其变形词添加到集合
  unmarkedWords.forEach(word => {
    const content = word.content.toLowerCase();
    const forms = getWordForms(content);
    forms.forEach(form => allUnmarkedForms.add(form));
  });
  
  console.log('未标记的单词形式:', Array.from(allUnmarkedForms));
  
  // 高亮文章中的未标记单词
  const unmarkedElements = highlightUnmarkedWords(allUnmarkedForms);
  
  // 创建一个防抖函数来处理滚动，避免多次连续滚动
  const scrollToElement = (element) => {
    // 先获取当前滚动位置
    const currentScrollTop = articleContentRef.value?.scrollTop || 0;
    
    // 获取元素相对于视口的位置
    const rect = element.getBoundingClientRect();
    // 获取文章容器相对于视口的位置
    const containerRect = articleContentRef.value?.getBoundingClientRect() || { top: 0 };
    
    // 计算元素相对于容器的位置
    const offsetTop = rect.top - containerRect.top + currentScrollTop;
    // 计算容器的可见高度
    const containerHeight = articleContentRef.value?.clientHeight || 0;
    
    // 计算目标滚动位置，使元素位于容器中央
    const targetScrollTop = offsetTop - (containerHeight / 2) + (rect.height / 2);
    
    // 平滑滚动到目标位置
    if (articleContentRef.value) {
      articleContentRef.value.scrollTo({
        top: targetScrollTop,
        behavior: 'smooth'
      });
    }
  };
  
  // 如果有未标记单词，滚动到第一个未标记的单词位置
  if (unmarkedElements.length > 0) {
    // 使用自定义滚动，而不是scrollIntoView
    scrollToElement(unmarkedElements[0]);
  }
  
  return unmarkedWords.map(w => w.content.toLowerCase());
};

// 高亮未标记的单词
const highlightUnmarkedWords = (unmarkedForms) => {
  const elements = [];
  
  // 处理文章中的单词
  document.querySelectorAll('.vocab-word.word-normal').forEach(el => {
    const wordContent = el.getAttribute('data-word');
    if (wordContent && unmarkedForms.has(wordContent.toLowerCase())) {
      // 添加闪烁动画效果
      el.classList.add('word-unmarked-focus');
      
      // 3秒后移除闪烁效果
      setTimeout(() => {
        el.classList.remove('word-unmarked-focus');
      }, 3000);
      
      elements.push(el);
    }
  });
  
  return elements;
};

// 在组件卸载时清理全局事件处理器和定时器
onBeforeUnmount(() => {
  // 移除事件监听器
  if (articleContentRef.value) {
    articleContentRef.value.removeEventListener('click', handleArticleClick);
    articleContentRef.value.removeEventListener('mouseover', handleWordHover);
    articleContentRef.value.removeEventListener('mouseout', handleWordHoverEnd);
  }
  
  // 清理所有单词的更新定时器
  wordUpdateTimers.forEach(timerId => clearTimeout(timerId));
  wordUpdateTimers.clear();
});

// 暴露方法给父组件
defineExpose({
  areAllWordsMarked,
  focusUnmarkedWords
});
</script>

<style scoped>
.article-section {
  background-color: white;
  color: #333;
  border-radius: 0.5rem 0 0 0.5rem;
  padding: 2rem;
  display: flex;
  flex-direction: column;
  overflow-y: auto;
  max-height: 100%;
  transition: width 0.2s ease;
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 0, 0, 0.2) transparent;
  position: relative;
}

.article-section::-webkit-scrollbar {
  width: 6px;
}

.article-section::-webkit-scrollbar-track {
  background: transparent;
}

.article-section::-webkit-scrollbar-thumb {
  background-color: rgba(0, 0, 0, 0.2);
  border-radius: 3px;
}

.article-title {
  font-size: 1.8rem;
  font-weight: 700;
  margin-bottom: 2rem;
  text-align: center;
  color: #222;
}

.ai-generated-label {
  display: inline-block;
  background: #f3f4f6;
  color: #1976d2;
  font-size: 0.95rem;
  border-radius: 4px;
  padding: 2px 10px;
  margin: 0 auto 1.2rem auto;
  text-align: center;
  box-shadow: 0 1px 4px rgba(25, 118, 210, 0.08);
  letter-spacing: 1px;
}

.article-content {
  font-size: 1.05rem;
  line-height: 1.7;
  position: relative;
}

/* 防止拖拽选择文本 */
.article-content::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: -1;
}

.paragraph {
  margin-bottom: 1.2rem;
  text-align: justify;
}

/* 单词高亮样式 */
:deep(.vocab-word) {
  @apply px-1 pb-1;
  cursor: pointer;
  border-radius: 8px;
  box-sizing: content-box;
  margin: 2px 0px;
  transition: all 0.2s ease;
  display: inline-block;
  user-select: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  -webkit-tap-highlight-color: transparent;
  position: relative;
}

:deep(.vocab-word:hover) {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

:deep(.vocab-word:active) {
  transform: translateY(0);
  box-shadow: none;
}

:deep(.word-normal) {
  background-color: rgba(158, 158, 158, 0.2);
  color: #616161;
}

:deep(.word-known) {
  background-color: rgba(76, 175, 80, 0.2);
  color: #2e7d32;
}

:deep(.word-fuzzy) {
  background-color: rgba(255, 193, 7, 0.2);
  color: #ff8f00;
}

:deep(.word-unknown) {
  background-color: rgba(244, 67, 54, 0.15);
  color: #c62828;
}

/* 单词状态图例 */
.word-status-legend {
  display: flex;
  /* position: sticky; */
  top: -2rem;
  left: -2rem;
  justify-content: center;
  gap: 0.8rem;
  border-radius: 4px;
  z-index: 10;
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(5px);
  -webkit-backdrop-filter: blur(5px);
  padding: 6px 10px;
  width:100%;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 0.3rem;
  font-size: 0.8rem;
  color: #333;
}

.status-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
}

.status-dot.normal {
  background-color: #9e9e9e;
}

.status-dot.known {
  background-color: #4caf50;
}

.status-dot.fuzzy {
  background-color: #ffc107;
}

.status-dot.unknown {
  background-color: #f44336;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .article-section {
    width: 100% !important;
    border-radius: 0.5rem 0.5rem 0 0;
    max-height: 50vh;
  }
}

/* 新的独立提示样式 */
.word-tooltip {
  position: fixed;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.85);
  color: white;
  padding: 8px 12px;
  border-radius: 4px;
  font-size: 0.95rem;
  z-index: 9999;
  pointer-events: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
  max-width: 200px;
  width: auto;
  word-wrap: break-word;
  white-space: normal;
  text-align: center;
  backdrop-filter: blur(4px);
  transition: opacity 0.15s ease;
  line-height: 1.4;
  opacity: 1;
}

.word-tooltip[style*="visibility: hidden"] {
  opacity: 0;
}

/* 未标记单词的闪烁效果 */
@keyframes unmarkedWordPulse {
  0% { 
    transform: translateY(0);
    box-shadow: 0 0 0 rgba(255, 0, 0, 0.2);
    background-color: rgba(255, 0, 0, 0.15);
  }
  50% { 
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(255, 0, 0, 0.3);
    background-color: rgba(255, 0, 0, 0.3);
  }
  100% { 
    transform: translateY(0);
    box-shadow: 0 0 0 rgba(255, 0, 0, 0.2);
    background-color: rgba(255, 0, 0, 0.15);
  }
}

:deep(.word-unmarked-focus) {
  animation: unmarkedWordPulse 0.8s ease-in-out infinite;
  border: 1px dashed #f44336;
  background-color: rgba(244, 67, 54, 0.15) !important;
  color: #c62828 !important;
}
</style>